package com.zlj.service.demo;


import java.awt.*;
import java.awt.event.InputEvent;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 用java代码模拟鼠标点击事件
 *
 * 思路：
 *      1、计算鼠标坐标
 *      2、创建一个定时任务
 *      3、调用系统鼠标点击事件
 * 扩展：
 */
public class ClickScheduleDemo {

    private Robot robot = null;


    private ClickScheduleDemo() {
        if (this.robot == null) {
            try {
                this.robot = new Robot();
            } catch (AWTException e) {
                e.printStackTrace();
            }
        }
    }

    static Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            ClickScheduleDemo demo = new ClickScheduleDemo();
            demo.task();
        }
    });



    /**
     * 定时调用鼠标点击事件任务
     */
    private void task() {
        Scanner sc = new Scanner(System.in);
        System.out.println("是否启动自动点击事件");
        int i = sc.nextInt();
        while (i != 0) {
            PointerInfo pointerInfo = MouseInfo.getPointerInfo();
            Point mousePointer = pointerInfo.getLocation();
            // 鼠标移动
            robot.mouseMove((int) mousePointer.getX(), (int) mousePointer.getY());
            // 鼠标按下左键
            robot.mousePress(InputEvent.BUTTON1_MASK);
            // 鼠标松开左键
            robot.mouseRelease(InputEvent.BUTTON1_MASK);
            try {
                thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) {

        //定时任务
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                thread.start();
            }
        }, 1000);//延迟5秒钟执行
    }

}
